package com.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.constant.RedisKey;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {
    private static String SECRET = "r!eQm@cWu#rEe$R";

    // private static int TOKEN_EXPIRED_DAY = 7;
    /**
     * 生产token
     */
    public static String getToken(Map<String, String> payload) {
        JWTCreator.Builder builder = JWT.create();

        //payload
        payload.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, RedisKey.TOKEN_EXPIRED_DAY); //默认7天过期

        builder.withExpiresAt(instance.getTime());//指定令牌的过期时间
        String token = builder.sign(Algorithm.HMAC256(SECRET));//签名
        return token;
    }

    /**
     * 验证token
     */
    public static DecodedJWT verify(String token) {
        //如果有任何验证异常，此处都会抛出异常
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT;
    }
    /**
     * 获取token中的 payload
     */
    @Deprecated
    public static String getUserId(String token) {
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        String userId = decodedJWT.getClaim("userId").asString();
        return userId;
    }

    public static void main(String[] args) {
        System.out.println(JWTUtils.getUserId("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMiIsImV4cCI6MTY1MzA2NTE1MX0.x-NmgHXv_-n9lHtXhVlft3ASmfjZe3LT58PcvUqxjsw"));
    }
}
